package com.hk.Mgr.web.controller.app;

import com.hk.Mgr.web.message.app.AssetAgreement;
import com.hk.Mgr.web.message.app.AssetDetailRes;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.DataUtil;
import com.hk.commons.JsonUtils;
import com.hk.commons.ResultCode;
import com.hk.commons.entity.Card;
import com.hk.commons.entity.UserCard;
import com.hk.commons.entity.order.OrderContract;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.service.kyc.ICard;
import com.hk.service.kyc.IUserCard;
import com.hk.service.order.IOrderContract;
import com.hk.service.order.IOrderInfo;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.ISysUser;
import com.hk.service.sys.impl.SysUserImpl;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Sheldon Chen on 2017/7/7.
 */
@Controller
@RequestMapping(value = BaseCtrl.App + "/assets")
public class AppAssetCtrl extends BaseCtrl {

    @Autowired
    private IOrderInfo orderInfoService;

    @Autowired
    private IProductInfo productInfoService;

    @Autowired
    private IUserCard userCardService;

    @Autowired
    private ISysUser sysUserService;

    @Autowired
    private ICard cardService;

    @Autowired
    private IOrderContract orderContractService;

    @Value("${activity.baseUrl}")
    private String activityUrl;

    @RequestMapping(value = "/{orderId}", method = RequestMethod.GET)
    @ResponseBody
    public ResponseBase getAsset(@PathVariable Long orderId) {
        ResponseBase responseBase = new ResponseBase();

        if (orderId == null) {
            responseBase.setResultCode(ResultCode.PARAM_ERROR.getCode());
            responseBase.setMsg("param error");
        } else {
            OrderInfo orderInfo = this.orderInfoService.findById(orderId);
            ProductInfo productInfo = this.productInfoService.findById(orderInfo.getProductId());
            SysUser sysUser = this.sysUserService.findById(orderInfo.getUserId());

            String cardDesc = null;
            String url = String.format("%sapi/couponWallet/%s/card/%s",
                    this.activityUrl, sysUser.getId(), orderInfo.getUserCardId());
            HttpGet httpGet = new HttpGet(url);
            HttpClient httpClient = HttpClients.createDefault();
            try {
                HttpResponse resp = httpClient.execute(httpGet);
                HttpEntity httpEntity = resp.getEntity();

                Map<String, Object> result = JsonUtils.toBean(EntityUtils.toString(httpEntity), Map.class);

                if (result != null) {
                    Map<String, Object> resultMap = (Map<String, Object>) result.get("result");
                    if (resultMap != null) {
                        String cardId = (String)resultMap.get("cardId");
                        logger.info("card id : " + cardId);

                        url = String.format("%sapi/coupon/%s",
                                this.activityUrl, cardId);
                        httpGet = new HttpGet(url);
                        httpClient = HttpClients.createDefault();
                        resp = httpClient.execute(httpGet);
                        httpEntity = resp.getEntity();

                        result = JsonUtils.toBean(EntityUtils.toString(httpEntity), Map.class);
                        if (result != null) {
                            resultMap = (Map<String, Object>)result.get("result");
                            if (resultMap != null) {
                                cardDesc = (String)resultMap.get("cardDesc");
                            }
                        }
                    }
                }

            } catch (Exception e) {
                logger.error("activity server error: ", e);
            }


            List<OrderContract> orderContracts = this.orderContractService.getOrderContractList(orderId);
            List<AssetAgreement> agreements = new ArrayList<>();
            for (OrderContract orderContract : orderContracts) {
                AssetAgreement assetAgreement = new AssetAgreement();
                assetAgreement.setTitle(orderContract.getContractTitle());
                assetAgreement.setUrl(orderContract.getContractHTMLUrl());

                agreements.add(assetAgreement);
            }

            AssetDetailRes assetDetailRes = new AssetDetailRes();

            assetDetailRes.setProductName(productInfo.getName());
            assetDetailRes.setOrderId(orderId.toString());
            assetDetailRes.setPayBackAmt(orderInfo.getPayBackAmt().toString());
            assetDetailRes.setProTerm(productInfo.getProTermStr());

            assetDetailRes.setUserRealName(DataUtil.getEncryptRealName(sysUser.getRealName()));
            assetDetailRes.setUserPhone(DataUtil.getEncryptPhoneNum(sysUser.getName()));
            assetDetailRes.setOrderCreatedOn(orderInfo.getOrderCreatedOn().toString());
            assetDetailRes.setOrderTradeDate(orderInfo.getOrderTradeDate() != null ? orderInfo.getOrderTradeDate().toString(): "");

            assetDetailRes.setDividendDate(orderInfo.getDividendDate() != null ? orderInfo.getDividendDate().toString(): "");
            assetDetailRes.setUserCardDesc(cardDesc != null ? cardDesc: "未加息");
            assetDetailRes.setProRate(orderInfo.getProRate().toString());
            assetDetailRes.setQryType(orderInfo.getConfirmStatus().toString());

            assetDetailRes.setAgreements(agreements);

            responseBase.setResultCode(ResultCode.SUCC.getCode());
            responseBase.setMsg("success");
            responseBase.setResult(assetDetailRes);
        }

        return responseBase;
    }

}
